//
//  VehicleInfoViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/11/29.
//  海外车信息

import UIKit
import YYKit

class ReserverInfo {
    var gender: NSInteger = -1
    var firstName: String = ""
    var lastName: String = ""
    var phone: String = ""
    var email: String = ""
    var agree: Bool = false
    init() {
            
    }
}

typealias BlockCarOrderSucceed = () ->Void
class VehicleInfoViewController: BaseViewController {
    //车辆下单成功刷新车辆详情
    var carOrderSucceedBlock: BlockCarOrderSucceed!
    
    var tableView: BaseTableView!
    var contentModel: CarDetailsContentModel!
    //var collectBtn: UIButton!
    var bgBavView: UIView!
    var seaCarFlag: Bool = false
    var totalPriceLab: UILabel!
    var protocolBtn: UIButton!
    var overView: WBPopOverView!
    var editorForm = ReserverInfo() //填写的信息
    var bottomView: UIView!
    var protocolLab: YYLabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.barBackgroundColor = .clear
        self.navBar.title = MMLocalizedString("reserved_wheel", comment: "预留车盘")

        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - TabbarHeight - NavBarHight - 50), style: .grouped)
        self.tableView.register(CarInfoTableViewCell.self, forCellReuseIdentifier: "CarInfoTableViewCell")
        self.tableView.register(ReserverInfoCell.self, forCellReuseIdentifier: "ReserverInfoCell")
        self.tableView.register(ReserverInfoPriceCell.self, forCellReuseIdentifier: "ReserverInfoPriceCell")
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "space")
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = .white
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.delaysContentTouches = true
        self.view.addSubview(self.tableView)
        
        self.createBottomView()
        self.fetchGetUserInfo()
    }
        
    private func createBottomView() {
        bottomView = UIView()
        bottomView.topBorder(width: 0.5, borderColor: Theme.lineColor)
        self.view.addSubview(bottomView)
       
        protocolBtn = UIButton()
        protocolBtn.setBackgroundImage(UIImage.init(named: "icon_check"), for: .normal)
        protocolBtn.setBackgroundImage(UIImage.init(named: "icon_agree"), for: .selected)
        protocolBtn.addTarget(self, action: #selector(protocolBtnAction), for: .touchUpInside)
        bottomView.addSubview(protocolBtn)
        
        
        protocolLab = YYLabel()
        protocolLab.textColor = Theme.titleLabColor
        protocolLab.backgroundColor = UIColor.clear
        protocolLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 13)
        protocolLab.numberOfLines = 0
        protocolLab.textAlignment = .left
        bottomView.addSubview(protocolLab)
        
        //登录
        let payBtn = UIButton()
        payBtn.setup_titleLabel(text: MMLocalizedString("pre_check", comment: "预定支付"))
        payBtn.setup_titleColor(color: UIColor.white)
        payBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColor), for: .normal)
        payBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColorHighLightColor), for: .highlighted)
        payBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        payBtn.layer.cornerRadius = 8
        payBtn.layer.masksToBounds = true
        payBtn.addTarget(self, action: #selector(payBtnAction), for: .touchUpInside)
        bottomView.addSubview(payBtn)
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.bottom.equalTo(IphoneXMarginBottom > 1 ? -IphoneXMarginBottom : -4)
        }

        protocolBtn.snp.makeConstraints { make in
            make.width.equalTo(20)
            make.height.equalTo(20)
            make.left.equalTo(14)
            make.top.equalTo(10)
        }
        
        protocolLab.snp.makeConstraints { make in
            make.left.equalTo(protocolBtn.snp.right).offset(10)
            make.top.equalTo(protocolBtn.snp.top)
            make.right.equalTo(-14)
            make.height.greaterThanOrEqualTo(20)
        }
        
        payBtn.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.top.equalTo(protocolLab.snp.bottom).offset(10)
            make.height.equalTo(46)
            make.bottom.equalTo(-4)
        }
        
        bottomView.layoutIfNeeded()
        
        let tempStr1 = MMLocalizedString("read_and_agree", comment: "已阅读并同意")
        let tempStr2 = MMLocalizedString("car_order_agreement", comment: "车辆订购协议》")
        let tempStr = String(format: "%@%@", tempStr1, tempStr2)
        let attStr = NSMutableAttributedString.init(string: tempStr)
        attStr.lineSpacing = 8
        
        attStr.addAttribute(NSAttributedStringKey.font, value: UIFont.init(name: Theme.PingFangSCMedium, size: 13)!, range: NSRange.init(location: tempStr1.count, length: tempStr2.count))
        attStr.setTextHighlight(NSRange.init(location: tempStr1.count, length: tempStr2.count), color: Theme.mainColor, backgroundColor: UIColor.clear, tapAction: { (containerView, attr, tRange, rect) in
            self.requestOrderAgreement()
        })
        self.protocolLab.attributedText = attStr
    }
    
    ///获取个人信息
    func fetchGetUserInfo(){
        guard UserModule.shared.isLogined == true else {
            return
        }
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.memberGetDetail, objectType: UserInfoResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! UserInfoResModel
            if resultObj.code == "1", let userData = resultObj.data {
                self.editorForm.email = userData.email ?? ""
                self.editorForm.phone = userData.phone ?? ""
                self.editorForm.firstName = userData.firstName ?? ""
                self.editorForm.lastName = userData.lastName ?? ""
                self.editorForm.gender = userData.gender ?? -1
                self.tableView.reloadData()
            }
            self.tableView.reloadData()
        } error: { err in
            self.view.handleLoading()
        }
    }
    
    ///订购协议
    private func requestOrderAgreement() {
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.orderAgreement(param: ["":""]), objectType: AboutUsResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! AboutUsResModel
            if resultObj.code == "1" {
                let vc = ProtocolViewController()
                vc.titleStr = MMLocalizedString("order_agreement", comment: "订购协议")
                vc.contentHtml = resultObj.data?.content ?? ""
                vc.modalPresentationStyle = .overFullScreen
                self.present(vc, animated: false)
                vc.backBlock = { [weak self] in
                    self?.protocolBtn.isSelected = true
                }
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    ///返回上一页
    @objc func backBtnAction(){
        self.navigationController?.popViewController(animated: true)
    }
    
    ///订购协议
    @objc func protocolBtnAction(){
        if self.protocolBtn.isSelected == false {
            self.requestOrderAgreement()
        }else{
            self.protocolBtn.isSelected = !self.protocolBtn.isSelected
        }
    }
    
    
    
    ///分享
    @objc func shareBtnAntion(sender: UIButton) {
        let VC = ShareViewController()
        VC.titleStr = MMLocalizedString("share", comment: "分享")
        VC.isfaceBook = true
        VC.shareContent = self.contentModel.shareText ?? ""
        VC.shareUrl = self.contentModel.shareText ?? ""
        VC.modalPresentationStyle = .overFullScreen
        self.present(VC, animated: false, completion: nil)
    }

    ///支付
    @objc func payBtnAction(){
        if UserModule.shared.isLogined == false {
            XTManageCenter.shared.jumpToLoginView()
            return
        }
        if self.contentModel == nil{
            return
        }
        if self.editorForm.gender == -1 {
            self.view.makeToast(message: MMLocalizedString("please_select_salutation", comment: "请选择称谓"))
            return
        }
        if self.editorForm.lastName == "" {
            self.view.makeToast(message: MMLocalizedString("add_input_last_name", comment: "请输入姓氏"))
            return
        }
        
        if self.editorForm.firstName == "" {
            self.view.makeToast(message: MMLocalizedString("add_input_first_name", comment: "请输入名字"))
            return
        }
        
        if self.editorForm.phone == "" {
            self.view.makeToast(message: MMLocalizedString("login_please_enter_phone", comment: "请输入手机号码"))
            return
        }
        
        if self.editorForm.email == "" {
            self.view.makeToast(message: MMLocalizedString("add_input_real_email", comment: "请输入正确的电邮地址"))
            return
        }
       
        if self.protocolBtn.isSelected == false{
            self.popOverView()
            return
        }
        self.requestUsedcarOrder()
    }
    
    
    ///去预订操作
    func requestUsedcarOrder() {
        self.view.showLoadingHUDText(nil)
        var param = NSMutableDictionary() as! [String: String]
        param["usedcarId"] = "\(self.contentModel?.id ?? 0)"
        param["salutation"] = "\(self.editorForm.gender)"
        param["lastName"] = self.editorForm.lastName
        param["firstName"] = self.editorForm.firstName
        param["phone"] = self.editorForm.phone
        param["email"] = self.editorForm.email
        if self.seaCarFlag {
            param["type"] = "3"
            param["orderPrice"] = "\(self.contentModel?.subscription ?? 0)"
        }else{
            param["orderPrice"] = "\(self.contentModel?.orderPrice ?? 0)"
        }

        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.usedcarOrder(param: param), objectType: ConfirmOrderModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! ConfirmOrderModel
            if resultObj.code == "1" {
                //刷新车辆详情
                self.carOrderSucceedBlock?()
                
                let tempOrder = OrderContentListModel()
                tempOrder.orderNo = resultObj.data?.orderNo ?? ""
                if self.seaCarFlag {
                    //海外车
                    tempOrder.price = self.contentModel?.subscription ?? 0
                }else{
                    //内地车
                    tempOrder.price = self.contentModel?.orderPrice ?? 0
                }
                let vc = PaymentViewController()
                vc.orderContentModel = tempOrder
                vc.modalPresentationStyle = .overFullScreen
                self.present(vc, animated: false)
                
                vc.pushFirstDataBlock = {[weak self] urlStr in
                    let vc = MyWebController()
                    vc.urlStr = urlStr
                    vc.titleStr = MMLocalizedString("confirm_first_pay", comment: "FirstData支付")
                    self?.navigationController?.pushViewController(vc, animated: false)
                }
                
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
   private func popOverView(){
        //获取labede的坐标在整个view上的位置
        var point = self.view.convert(self.protocolBtn.center, fromViewOrWindow: self.bottomView!)
        point.y = point.y - 10
        let tipLab = UILabel(frame: CGRect(x: 14, y: 10, width: kScreenWidth*2/3 - 24, height: 100))
        tipLab.text = MMLocalizedString("subscription_agreement", comment: "请阅读并同意车辆订购协议")
        tipLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 13)
        tipLab.textColor = Theme.whiteColor
        tipLab.numberOfLines = 0
        tipLab.lineBreakMode = .byTruncatingTail
        tipLab.sizeToFit()
        
        var tempW = tipLab.frame.size.width + 28
        if tempW > kScreenWidth * 2/3 {
            tempW = kScreenWidth * 2/3
        }
        
        if tempW < 120 {
            tempW = 120
        }
        if self.overView != nil {
            self.overView = nil
        }
        overView = WBPopOverView.init(origin: point, width: tempW, height: Float(tipLab.frame.size.height) + 20, direction: WBArrowDirection.down1)
        overView?.backgroundColor = UIColor.init(hex: 0xffffff, alpha: 0.1)
        overView?.backView.backgroundColor = Theme.titleLabColor
        overView?.backView.layer.masksToBounds = true
        overView?.backView.layer.cornerRadius = 4
        overView?.backView.addSubview(tipLab)
        overView?.pop()
    }
    
    
    ///MARK: - Antion
    func jumpToLogin(){
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let vc = LoginViewController()
        let loginNavi = BaseNavigationController.init(rootViewController: vc)
        loginNavi.modalPresentationStyle = .fullScreen
        tabbarVC.present(loginNavi, animated: true)
    }
    
}
extension VehicleInfoViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
            return 50
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: "CarInfoTableViewCell", for: indexPath) as! CarInfoTableViewCell
                cell.seaCarFlag = self.seaCarFlag
                cell.setModel(model: self.contentModel)
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "ReserverInfoCell", for: indexPath) as! ReserverInfoCell
                cell.setReserverInfoCell(data: self.editorForm)
                cell.delegate = self
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            case 2:
                let cell = tableView.dequeueReusableCell(withIdentifier: "ReserverInfoPriceCell", for: indexPath) as! ReserverInfoPriceCell
                cell.seaCarFalg = self.seaCarFlag
                cell.setReserverInfoPriceCell(model: self.contentModel)
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "space", for: indexPath)
                return cell
        }
    }
}


extension VehicleInfoViewController: UIScrollViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
        self.view.resignFirstResponder()
    }
}

///0：女士、1：先生、2：小姐
extension VehicleInfoViewController: ReserverInfoCellDelegate {
    func didSelectGender() {
        let vc = MHPickerSheetView()
        vc.modalPresentationStyle = .overFullScreen
        vc.titleStr = MMLocalizedString("please_select", comment: "请选择")
        vc.dataArray = [
            MMLocalizedString("add_gender_Mrs", comment: "女士"),
            MMLocalizedString("add_gender_Mr", comment: "先生"),
            MMLocalizedString("add_gender_Miss", comment: "小姐")
        ]
        vc.selectIndex = self.editorForm.gender
        vc.callBack = {[weak self] (brandItem, vIndex, configFlag) in
            guard configFlag else {
                //取消
                return
            }
            self?.editorForm.gender = vIndex
            self?.tableView.reloadData()
        }
        self.present(vc, animated: false, completion: nil)
    }
}
